﻿using ApiCommon;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace WeiXinMongoApis.Controllers
{
    public class SpecifyAuthorizationController : ApiController
    {
        /// <summary>
        /// 特殊授权者名单的文件名
        /// </summary>
        const string SpecifyAuthorizationUsersFileName = "SpecifyAuthorizationUsers.txt";

        // GET api/values/5
        public SpecifyAuthorization Get(string clientId)
        {
            //开始日
            DateTime fromDate = DateTime.MinValue;
            //到期日
            DateTime toDate = DateTime.MinValue;

            //剩余天数
            double remainingDays = 0;

            using (FileStream file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SpecifyAuthorizationUsersFileName), FileMode.OpenOrCreate))
            {
                StreamReader sr = new StreamReader(file);
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] cols = line.Split(',');
                    if (cols[0] == clientId)
                    {
                        fromDate = DateTime.Parse(cols[1]);
                        toDate = DateTime.Parse(cols[2]);
                        remainingDays = (toDate - DateTime.Now.Date).TotalDays;
                    }
                }
            }

            return new SpecifyAuthorization() { 
                FromDate=fromDate,  
                ToDate = toDate, 
                RemainingDays = (int)remainingDays 
            };
        }
    }
}
